package com.explorati.LeetCode003.lengthOfLongestSubstring;

import java.util.HashSet;
import java.util.Set;

/**
 * 3. Longest Substring Without Repeating Characters
 * 
 * Given a string, find the length of the longest substring without repeating
 * characters.
 * 
 * 
 * Input: "abcabcbb" Output: 3 
 * Explanation: The answer is "abc", with the length of 3.
 * 
 * @author explorati
 *
 */
public class Solution1 {
	public int lengthOfLongestSubstring(String s) {
		int n = s.length();
		Set<Character> set = new HashSet<>();
		int ans = 0, i = 0, j = 0;
		while (i < n && j < n) {
			if (!set.contains(s.charAt(j))) {
				set.add(s.charAt(j++));
				ans = Math.max(ans, j - i);
			} else {
				set.remove(s.charAt(i++));
			}

		}
		return ans;
	}
}
